/**
 * 基于ajaxform.js上传组件
 * Copyright (c) 2013 vakinge@gmail.com
 * */
;(function($) {
	$.fn.ajaxUploader = function(options) {
		var settings = {
	            form_selecter: 'form',
	            action_url: '',
	            input_name: 'file',
	            allowExts: '.jpg,.gif,.png',
	            onSubmit: function(id, fileName){},
	            onFinish: function(fileName){}
	    };
	    if(options) {$.extend(settings, options);}
	        
		var $target = $(this),$attachType = $target.attr('attach-type');
		$target.on('change',function(){
			var fileName = $target.val();
			var fileType = (fileName.substring(fileName.lastIndexOf(".")+1,fileName.length)).toLowerCase();
			if(".jpg,.gif,.png".indexOf(fileType) < 0){
				$.error('文件类型不支持');return;
			}
			var $form = $(settings.form_selecter);
			$form.find('[name]').attr('disabled',true);
			$form.attr('enctype','multipart/form-data');
			$target.attr('name',settings.input_name);
			if($attachType){
				$form.append('<input id="attachType" type="hidden" name="type" value="'+$attachType+'" />');
			}
			$form.ajaxSubmit({
				  dataType:"JSON",
				  url:settings.action_url,
				  success:function(data) {
				     $form.find('[name]').removeAttr("disabled"); 
			         $target.removeAttr('name');
			         $form.removeAttr('enctype');
			         $form.remove("#attachType");
						 if(data.status == 1){
							$.success(data.msg);
							$target.attr('finished','1');
							settings.onFinish(data.data);
						 }else{
							$.error( data.msg);	
						 }
				  },
				  error: function (data, status, e){
					  $form.find('[name]').removeAttr("disabled"); 
				      $target.removeAttr('name');
				      $form.removeAttr('enctype');
				      $form.remove("#attachType");
					  $.error(e);
				  }
			});
		});
		return this;
	};
})(jQuery);